<template>
  <el-form ref="formRef"  label-width="80px">
    <el-form-item label="活动名称">
      {{info.title}}
    </el-form-item>
    <el-form-item label="活动状态">
      {{info.status}}
    </el-form-item>
    <el-form-item label="活动描述">
      {{info.description}}
    </el-form-item>
    <el-form-item label="活动时间">
      {{info.start_time}} - {{info.end_time}}
    </el-form-item>
    <el-form-item label="操作" >
      <el-button type="success" v-if="info.status === '正在进行'" @click="start">开始抽奖</el-button>
      <el-button type="warning" @click="resetActivity">重置结果</el-button>
      <el-button @click="closeTag">返回</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="prize" style="width: 100%">
    <el-table-column prop="name" label="奖项" width="180" />
    <el-table-column prop="count" label="名额" width="180" />
    <el-table-column prop="award" label="奖品" />
  </el-table>
  <br>
  <pro-table
    ref="table"
    title="参与成员"
    :request="getList"
    :columns="columns"
    :search="searchConfig"
    :pagination="paginationConfig"
    @selectionChange="handleSelectionChange"
  >
    <!-- 工具栏 -->
    <template #toolbar>
      <el-button type="primary" icon="el-icon-delete" @click="batchDelete">
        批量删除
      </el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="refresh">
        刷新
      </el-button>
    </template>
    <template #operate="scope">
      <el-popconfirm title="Are you sure to delete this?" @confirm="delUsers(scope.row.id)">
        <template #reference>
          <el-button size="mini" type="danger">Delete</el-button>
        </template>
      </el-popconfirm>
    </template>
  </pro-table>
</template>

<script>
import { defineComponent, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { delActivityUsers, getActivity, getActivityUsers, resetActivityPalm } from "../../api/activity";
import useCloseTag from "../../hooks/useCloseTag";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  name: 'ActivityManage',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const { closeTag } = useCloseTag()
    const state = reactive({
      prize: [],
      users: [],
      palm: [],
      info: {},
      aid: route.params.id,
      // 表格列配置，大部分属性跟el-table-column配置一样
      columns: [
        { type: 'selection' },
        { label: '序号', prop: 'id' },
        { label: '氏族', prop: 'team' },
        { label: '名称', prop: 'nickname', sortable: true, width: 180 },
        { label: '参与时间', prop: 'create_time' },
        {
          label: '操作',
          fixed: 'right',
          width: 80,
          align: 'center',
          tdSlot: 'operate', // 自定义单元格内容的插槽名称
        },
      ],
      // 搜索配置
      searchConfig: {
        labelWidth: '90px', // 必须带上单位
        inputWidth: '360px', // 必须带上单位
        fields: [
          {
            type: 'text',
            label: '成员ID',
            name: 'nickname',
          },
          {
            label: '氏族',
            name: 'team',
            type: 'radio-button',
            options: [
              {
                name: '一团',
                value: 1,
              },
              {
                name: '二团',
                value: 2,
              },
              {
                name: '三团',
                value: 3,
              },
              {
                name: '四团',
                value: 4,
              },
            ],
          },
        ],
      },
      // 分页配置
      paginationConfig: {
        layout: 'total, prev, pager, next, sizes', // 分页组件显示哪些功能
        pageSize: 5, // 每页条数
        pageSizes: [5, 10, 20, 50],
        style: { textAlign: 'left' },
      },
      selectedItems: [],
      batchDelete() {
        console.log(state.selectedItems)
      },
      // 选择
      handleSelectionChange(arr) {
        state.selectedItems = arr
      },
      // 请求函数
      async getList(params) {
        params.id = state.aid
        // params是从组件接收的，包含分页和搜索字段。
        const { data } = await getActivityUsers(params)
        state.users = data.list
        // 必须要返回一个对象，包含data数组和total总数
        return {
          data: data.list,
          total: +data.total,
        }
      },
    })
    const table = ref(null)
    const refresh = () => {
      table.value.refresh()
    }
    const methods = {
      async getActivityInfo() {
        let resp = await getActivity(state.aid)
        state.prize = resp.data.data.prize
        state.info = resp.data.data
        state.palm = resp.data.data.palm
      },
      async delUsers(aid) {
        let resp = await delActivityUsers(aid)
        if(resp.code !== 200){
          ElMessage({
            message: resp.message || '服务器错误！',
            type: 'error',
          })
        }else {
          table.value.refresh()
          ElMessage({
            message: resp.message || 'ok',
            type: 'success',
          })
        }
      },
      resetActivity() {
        ElMessageBox.confirm(
          '重置会清空所有抽奖结果，无法撤销！',
          '确定要重置吗？',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(async function () {
            let resp = await resetActivityPalm(state.aid)
          if (resp.code !== 200) {
            ElMessage({
              message: resp.message || '服务器错误！',
              type: 'error',
            })
          } else {
            localStorage.removeItem('players')
            localStorage.removeItem('result')
            ElMessage({
              message: resp.message || 'ok',
              type: 'success',
            })
          }

        });
      },
      start() {
        let member = []
        state.users.map(item => {
          member.push({
            'id' : item.id,
            'name' : item.nickname
          })
        })
        // for (var i = 1; i < 201; i++) {
        //   member.push(
        //     {
        //       "id": i,
        //       name: i + "号"
        //     }
        //   )
        // }
        localStorage.setItem('awards', JSON.stringify(state.prize))
        localStorage.setItem('members', JSON.stringify(member))
        localStorage.setItem('players', JSON.stringify(member))//奖池人员
        localStorage.setItem('luckyFellow', JSON.stringify([]))
        localStorage.setItem('result', JSON.stringify(state.palm || []))
        localStorage.setItem(
          'batchNumber',
          JSON.stringify(20)
        )
        router.push('/activity/details/' + state.aid)
      }
    }
    onMounted(() => {
      methods.getActivityInfo()
    })
    return { ...toRefs(state), refresh, table, ...methods, closeTag }
  },
})
</script>
